<?php
include 'library.php';
include "classes/class.phpmailer.php"; 

// Helper method to get a string description for an HTTP status code
// From http://www.gen-x-design.com/archives/create-a-rest-api-with-php/ 
function getStatusCodeMessage($status)
{
    // these could be stored in a .ini file and loaded
    // via parse_ini_file()... however, this will suffice
    // for an example
    $codes = Array(
        100 => 'Continue',
        101 => 'Switching Protocols',
        200 => 'OK',
        201 => 'Created',
        202 => 'Accepted',
        203 => 'Non-Authoritative Information',
        204 => 'No Content',
        205 => 'Reset Content',
        206 => 'Partial Content',
        300 => 'Multiple Choices',
        301 => 'Moved Permanently',
        302 => 'Found',
        303 => 'See Other',
        304 => 'Not Modified',
        305 => 'Use Proxy',
        306 => '(Unused)',
        307 => 'Temporary Redirect',
        400 => 'Bad Request',
        401 => 'Unauthorized',
        402 => 'Payment Required',
        403 => 'Forbidden',
        404 => 'Not Found',
        405 => 'Method Not Allowed',
        406 => 'Not Acceptable',
        407 => 'Proxy Authentication Required',
        408 => 'Request Timeout',
        409 => 'Conflict',
        410 => 'Gone',
        411 => 'Length Required',
        412 => 'Precondition Failed',
        413 => 'Request Entity Too Large',
        414 => 'Request-URI Too Long',
        415 => 'Unsupported Media Type',
        416 => 'Requested Range Not Satisfiable',
        417 => 'Expectation Failed',
        500 => 'Internal Server Error',
        501 => 'Not Implemented',
        502 => 'Bad Gateway',
        503 => 'Service Unavailable',
        504 => 'Gateway Timeout',
        505 => 'HTTP Version Not Supported'
    );

    return (isset($codes[$status])) ? $codes[$status] : '';
}

// Helper method to send a HTTP response code/message
function sendResponse($status = 200, $body = '', $content_type = 'text/html')
{
    $status_header = 'HTTP/1.1 ' . $status . ' ' . getStatusCodeMessage($status);
    header($status_header);
    header('Content-type: ' . $content_type);
    echo $body;
}

class UnlockAPI {

    private $db;
	
    // Constructor - open DB connection
    function __construct() {
        $this->db = new mysqli('mysql.otep.ws', 'listerine_dba', 'XkA8pw9dMX', 'otep_coachmouth');
		//$this->db = new mysqli('localhost', 'root', '', 'coachmouth');
        $this->db->autocommit(TRUE);
    }

    // Destructor - close DB connection
    function __destruct() {
        $this->db->close();
    }

    // Main method to redeem a code
    function unlock() {
    
        // Check for required parameters
        if (isset($_POST["user_id"]) && isset($_POST["reward_day"])) {
        
			// Check promo Period
			$today = new DateTime();
			$today = $today->format('Y-m-d H:i:s');
			
			$period = new DateTime('2014-09-02 18:00:00');
			$period = $period->format('Y-m-d H:i:s');
			if($today > $period){
				 $result = array(
					"success" => 0,
					"error" => 'Promo Period Ended',
				);
				sendResponse(200, json_encode($result));
                return false;
			}
			
            // Put parameters into local variables
			
            $user_id = $_POST["user_id"];
            $reward_day = $_POST["reward_day"];
            if($reward_day == 7 )
			{
				$reward_day = 1;
			}
			 if($reward_day == 14 )
			{
				$reward_day = 2;
			}
			 if($reward_day == 21 )
			{
				$reward_day = 3;
			}


            //Look up email
            //Look up user in database
			$stmt = $this->db->prepare('SELECT id, name, email FROM users WHERE id=?');
            $stmt->bind_param("i", $user_id);
            $stmt->execute();
            $stmt->bind_result($id, $name, $email);
            while ($stmt->fetch()) {
                break;
            }
            $stmt->close();
            
            
            // Look up reward in database
            $stmt = $this->db->prepare('SELECT id FROM rewards WHERE reward_day=?');
            $stmt->bind_param("i", $reward_day);
            $stmt->execute();
            $stmt->bind_result($id);
            while ($stmt->fetch()) {
                break;
            }
            $stmt->close();
            
            // Bail if reward doesn't exist
            if ($id <= 0) {
                 $result = array(
					"success" => 0,
					"error" => 'Invalid Reward',
				);
				sendResponse(200, json_encode($result));
                return false;
            }
            //Check if User already unlocked the reward
			$stmt = $this->db->prepare('SELECT id, rw_promo_code_id, user_id, reward_day FROM rw_promo_code_unlocked WHERE user_id=? and reward_day = ?');
            $stmt->bind_param("ii", $user_id, $reward_day);
            $stmt->execute();
            $stmt->bind_result($rid, $code_id, $user_id, $reward_day);
            while ($stmt->fetch()) {
                break;
            }
            $stmt->close();
			
			// Bail if user already unlocked a reward
            if ($rid > 0) {
            	// Retrieve code in database
           		$stmt = $this->db->prepare('SELECT id, code FROM rw_promo_code WHERE id=?');
            	$stmt->bind_param("i", $code_id);
            	$stmt->execute();
            	$stmt->bind_result($code_id, $code);
            	while ($stmt->fetch()) {
                	break;
           	 	}
           	 	$stmt->close();
           	 	$unlocked = "yes";
           	 }
           	 else{
            	// Look up code in database
            	$stmt = $this->db->prepare('SELECT id, code, unlocked FROM rw_promo_code WHERE reward_id=? and unlocked = 0');
            	$stmt->bind_param("i", $id);
            	$stmt->execute();
            	$stmt->bind_result($code_id, $code, $unlocked);
            	while ($stmt->fetch()) {
                	break;
            	}
            	$stmt->close();
            	$unlocked = "no";
            	// Bail if no more reward
            	if ($code_id < 0) {
                	$result = array(
					"success" => 0,
					"error" => 'Promo Period Ended',
					);
					sendResponse(200, json_encode($result));
                	return false;
            	}
            }
            // Add tracking of unlocked
            $stmt = $this->db->prepare("INSERT INTO rw_promo_code_unlocked (rw_promo_code_id, user_id, reward_day) VALUES (?, ?, ?)");
            $stmt->bind_param("iii", $code_id, $user_id, $reward_day);
            $stmt->execute();
            $stmt->close();
            
            // Increment use of code
            $this->db->query("UPDATE rw_promo_code SET unlocked=unlocked+1 WHERE id=".$code_id);
            $this->db->commit();
            
            //Send email to users
			switch ($reward_day)
			{
				case "1":
  					$message = "Good job, you’ve had a great start so far! You deserve to treat yourself to a movie. Present the coupon you unlocked in any SM Cinema branch and you will be given a Php 100.00 discount on the movie of your choice. \r\nEnjoy your movie but don’t forget tomorrow, bright and early, your training resumes.";

					$mail = new PHPMailer(); // create a new object
					$mail->IsSMTP(); // enable SMTP
					$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
					$mail->SMTPAuth = true; // authentication enabled
					$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
					$mail->Host = "smtp.gmail.com";
					$mail->Port = 465; // or 587
					$mail->IsHTML(true);
					$mail->Username = "coachmouthph@gmail.com";
					$mail->Password = "listerinecoachmouthPH";
					$mail->SetFrom("coachmouthph@gmail.com");
					$mail->FromName = "Listerine Coach Mouth";
					$mail->Subject = "Listerine Coach Mouth 7th Day Reward";
					$mail->Body = "GREAT JOB MACHO MOUTH! Now that your mouth is powered up, why don&apos;t you go on a movie date? As a prize for your superb rinsing, there&apos;s a Php 100.00 discount at SM Cinema in the rewards tab of your app. Just present the coupon you unlocked at any SM Cinema branch and get a discount on the movie of your choice. Enjoy your movie but don&apos;t forget, training resumes tomorrow!<br/><br/><p align='right'><b>Coach Mouth</b></p>";
					$mail->AddAddress($email);
 					if(!$mail->Send()){
    					$sent = "error";
					}
					else{
    					$sent = "Message has been sent";
					}
  					break;
				case "2":
  					$mail = new PHPMailer(); // create a new object
					$mail->IsSMTP(); // enable SMTP
					$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
					$mail->SMTPAuth = true; // authentication enabled
					$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
					$mail->Host = "smtp.gmail.com";
					$mail->Port = 465; // or 587
					$mail->IsHTML(true);
					$mail->Username = "coachmouthph@gmail.com";
					$mail->Password = "listerinecoachmouthPH";
					$mail->SetFrom("coachmouthph@gmail.com");
					$mail->FromName = "Listerine Coach Mouth";
					$mail->Subject = "Listerine Coach Mouth 14th Day Reward";
					$mail->Body = "WOW! Great job power rinser. Don&apos;t you feel your mouth getting stronger? You must be running low on your Listerine, let me mail you one for free so we can continue your training. Reply with your full name, age and mailing address and I&apos;ll send you a 250 ml bottle of Listerine. Let&apos;s keep pushing that mouth to the limit. See you at tomorrow&apos;s training!<br/><br/><p align='right'><b>Coach Mouth</b></p><br/><br/>FINE PRINT<br/><i>Please reply with your full name, age and mailing address within 14 days to claim the prize. Prizes of participants&apos; who do not respond with their mailing address within 14 days will be forfeited.</i>";
					$mail->AddAddress($email);
 					if(!$mail->Send()){
    					$sent = "error";
					}
					else{
    					$sent = "Message has been sent";
					}
  					break;
				case "3":
  					$mail = new PHPMailer(); // create a new object
					$mail->IsSMTP(); // enable SMTP
					$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
					$mail->SMTPAuth = true; // authentication enabled
					$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
					$mail->Host = "smtp.gmail.com";
					$mail->Port = 465; // or 587
					$mail->IsHTML(true);
					$mail->Username = "coachmouthph@gmail.com";
					$mail->Password = "listerinecoachmouthPH";
					$mail->SetFrom("coachmouthph@gmail.com");
					$mail->FromName = "Listerine Coach Mouth";
					$mail->Subject = "Listerine Coach Mouth 21st Day Reward";
					$mail->Body = "Hey power mouth! You reached the 21-day mark. You deserve a reward. So here&apos;s another movie Php 100.00 movie coupon. Just present the coupon you unlocked at any SM cinema branch and get a discount on the movie of your choice. After that, keep your training going to keep your mouth powered up!<br/><br/><p align='right'><b>Coach Mouth</b></p>";
					$mail->AddAddress($email);
 					if(!$mail->Send()){
    					$sent = "error";
					}
					else{
    					$sent = "Message has been sent";
					}
  					break;
			}
			
			// Return code, encoded with JSON
            $result = array(
                "code" => $code,
                "id" => $id,
				"success" => 1,
				"emailsent" => $sent,
				"unlocked" => $unlocked,
            );
            sendResponse(200, json_encode($result));
            return true;
        }
        sendResponse(400, 'Invalid request');
        return false;
    
    }

}

// This is the first thing that gets called when this page is loaded
// Creates a new instance of the RedeemAPI class and calls the redeem method
$api = new UnlockAPI;
$api->unlock();

?>